package com.wthink.hzgj.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.appcompat.widget.TintTypedArray;

import com.wthink.hzgj.R;



public class MarqueeView extends View implements Runnable {
    private String string;
    private float speed = 1;//移动速度
    private int textColor = Color.BLACK;//文字颜色,默认黑色
    private float textSize = 12;//文字颜色,默认黑色
    private int textdistance;
    private int textDistance1 = 10;
    private String black_count = "";//间距转化成空格距离
    private float startLocationDistance = 1.0f;//开始的位置选取，百分比来的，距离左边，0~1，0代表不间距，1的话代表，从右面，1/2代表中间。
    private float xLocation = 0;//文本的x坐标
    private int contentWidth;//内容的宽度
    private float oneBlack_width;//空格的宽度

    private TextPaint paint;//画笔
    private Rect rect;

    private int repetCount = 0;//
    private boolean resetInit = true;

    private Thread thread;
    private String content = "";

    private float textHeight;


    public MarqueeView(Context context) {
        this(context, null);
    }

    public MarqueeView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MarqueeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initattrs(attrs);
        initpaint();
    }

    @SuppressLint("RestrictedApi")
    private void initattrs(AttributeSet attrs) {
        TintTypedArray tta = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
                R.styleable.MarqueeView);
        textColor = tta.getColor(R.styleable.MarqueeView_marqueeview_text_color, textColor);
        speed = tta.getFloat(R.styleable.MarqueeView_marqueeview_text_speed, speed);
        textSize = tta.getFloat(R.styleable.MarqueeView_marqueeview_text_size, textSize);
        textDistance1 = tta.getInteger(R.styleable.MarqueeView_marqueeview_text_distance, textDistance1);
        startLocationDistance = tta.getFloat(R.styleable.MarqueeView_marqueeview_text_startlocationdistance, startLocationDistance);
        tta.recycle();
    }

    private void initpaint() {
        rect = new Rect();
        paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(textColor);
        paint.setTextSize(dp2px(textSize));

    }

    public int dp2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (resetInit) {
            setTextDistance(textDistance1);
            if (startLocationDistance < 0) {
                startLocationDistance = 0;
            } else if (startLocationDistance > 1) {
                startLocationDistance = 1;
            }
            xLocation = getWidth() * startLocationDistance;
            resetInit = false;
        }

        if (xLocation < 0) {
            int beAppend = (int) ((-xLocation) / contentWidth);
            if (beAppend >= repetCount) {
                repetCount++;
                string = string + content;
            }
        }
        if (repetCount == 50) {
            resetInit = true;
            repetCount = 0;
            string = "";
        }
        if (string != null) {
            canvas.drawText(string, xLocation, getHeight() / 2 + textHeight / 2, paint);
        }

    }

    @Override
    public void run() {
        while (!TextUtils.isEmpty(content)) {
            try {
                Thread.sleep(10);
                xLocation = xLocation - speed;
                postInvalidate();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    public void continueRoll() {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
//            thread.interrupt();
//            thread = null;
        }
    }

    /**
     * 设置文字间距
     *
     * @param textdistance2
     */
    public void setTextDistance(int textdistance2) {

        String black = " ";
        oneBlack_width = getBlacktWidth();
        textdistance2 = dp2px(textdistance2);
        int count = (int) (textdistance2 / oneBlack_width);
        if (count == 0) {
            count = 1;
        }
        textdistance = (int) (oneBlack_width * count);
        black_count = "";
        for (int i = 0; i <= count; i++) {
            black_count = black_count + black;
        }
        setContent(content);
    }

    /**
     * 计算出一个空格的宽度
     *
     * @return
     */
    private float getBlacktWidth() {
        String text1 = "en en";
        String text2 = "enen";
        return getContentWidth(text1) - getContentWidth(text2);

    }

    private float getContentWidth(String black) {
        if (black == null || black == "") {
            return 0;
        }

        if (rect == null) {
            rect = new Rect();
        }
        paint.getTextBounds(black, 0, black.length(), rect);
        textHeight = getContentHeight();

        return rect.width();
    }

    private float getContentHeight() {
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        return Math.abs((fontMetrics.bottom - fontMetrics.top)) / 2;
    }

    /**
     * 设置文字颜色
     *
     * @param textColor
     */
    public void setTextColor(int textColor) {
        if (textColor != 0) {
            this.textColor = textColor;
            paint.setColor(getResources().getColor(textColor));
        }
    }

    /**
     * 设置文字大小
     *
     * @param textSize
     */
    public void setTextSize(float textSize) {
        if (textSize > 0) {
            this.textSize = textSize;
            paint.setTextSize(dp2px(textSize));
            contentWidth = (int) (getContentWidth(content) + textdistance);
        }
    }

    /**
     * 设置滚动速度
     *
     * @param speed
     */
    public void setTextSpeed(float speed) {
        this.speed = speed;
    }

    public void setContent(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        xLocation = getWidth() * startLocationDistance;
        if (!str.endsWith(black_count)) {
            str = str + black_count;
        }
        this.content = str;
        contentWidth = (int) (getContentWidth(content) + textdistance);
        repetCount = 0;
        int contentCount = (getWidth() / contentWidth) + 2;
        this.string = "";
        for (int i = 0; i <= contentCount; i++) {
            this.string = this.string + this.content;
        }
        continueRoll();
    }

}